<?php

function success_common($_code)
{
    $error_data['rcode'] = $_code;
    $result = json_encode($error_data);

    return pr($result);
}

function error_common($_this, $_line, $_error_code)
{
    $error_data['name'] = $_this->name;
    $error_data['line'] = $_line;
    $error_data['rcode'] = $_error_code;

    $result = json_encode($error_data);

    return pr($result);
}

function gcm_push($_data, $_push_id)
{
    $data = array(
        'contentTitle' => $_data['title'],
        'contentText' => $_data['msg']
    );

    $fields = array
    (
        'registration_ids' => $_push_id,
        'data' => $data,
    );

    $headers = array(
        'Authorization: key=' . GCM_KEY,
        'Content-Type: application/json; charset=UTF-8;'
    );

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, GCM_URL);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));

    $result = curl_exec($ch);

    if($result === FALSE)
    {
        //pr('Curl failed:' . curl_error($ch));
        die('Curl failed: ' . curl_error($ch));
    }

    $result = json_decode($result, true);
    //pr('Success : ' . $result['success'] . ', Fail : ' . $result['failure']);
    curl_close($ch);

    if(!empty($result['failure']))
    {
        return FALSE;
    }
    return TRUE;
}

function apns_push($_data, $_push_id)
{
    $message = $_data['msg'];

    $file_read = new File(WWW_ROOT . 'apns_files' .DS . APNS_PEM_NAME);
    $apns_cert = $file_read->path;

    $apns_host = APNS_URL_DEV; // APNS_URL(실서비스), APNS_URL_DEV(개발)
    $apns_port = 2195;

    $payload = array('aps' => array('alert' => $message, 'badge' => 0, 'sound' => 'default'));
    $payload = json_encode($payload);

    $streamContext = stream_context_create();
    stream_context_set_option($streamContext, 'ssl', 'local_cert', $apns_cert);

    $apns = stream_socket_client('ssl://' . $apns_host . ':' . $apns_port, $error, $errorString, 60, STREAM_CLIENT_CONNECT, $streamContext);

    if(!$apns)
    {
        pr("Failed to connect : " . $error . ', ' . $errorString);
    }

    foreach($_push_id as $device_token)
    {
        $apns_message = chr(0).chr(0).chr(32).pack('H*', str_replace(' ', '', $device_token)).chr(0).chr(strlen($payload)).$payload;
        $writeResult = fwrite($apns, $apns_message);

        if($writeResult != 111)
        {
            fclose($apns);

            $streamContext = stream_context_create();
            stream_context_set_option($streamContext, 'ssl', 'local_cert', $apns_cert);

            $apns = stream_socket_client('ssl://' . $apns_host . ':' . $apns_port, $error, $errorString, 60, STREAM_CLIENT_CONNECT, $streamContext);

            if(!$apns)
            {
                pr("Failed to connect : " . $error . ', ' . $errorString);
            }
        }

    }

    fclose($apns);

    return TRUE;
}

function now_time()
{
    $now_time = date("Y-m-d H:i:s",time());
    return $now_time;
}

function array_to_json($array)
{
    if(!is_array($array))
    {
        return false;
    }

    $associative = count(array_diff(array_keys($array), array_keys(array_keys($array))));
    if($associative)
    {
        $construct = array();
        foreach($array as $key => $value)
        {
            if(is_numeric($key))
            {
                $key = "key_$key";
            }

            $key = '"'.addslashes($key).'"';

            if(is_array($value))
            {
                $value = arrayToJson($value);
            }
            else if(!is_numeric($value) || is_string($value))
            {
                $value = '"'.addslashes($value).'"';
            }

            $construct[] = "$key:$value";
        }

        $result = "{" . implode(",", $construct) . "}";

    }
    else
    {
        $construct = array();

        foreach($array as $value)
        {
            if(is_array($value))
            {
                $value = arrayToJson($value);
            }
            else if(!is_numeric($value) || is_string($value))
            {
                $value = '"'.addslashes($value).'"';
            }

            $construct[] = $value;
        }

        $result = "[" . implode( ",", $construct) . "]";
    }

    return $result;
}
